package com.avcdata.aoscustommade.activity;

import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.avcdata.aoscustommade.R;
import com.avcdata.aoscustommade.adapter.BaseHolderAdapter;
import com.avcdata.aoscustommade.bean.LocatityCacheData;
import com.avcdata.aoscustommade.bean.TopBrandAndSelfBrandBean;
import com.avcdata.aoscustommade.bean.UserRegionBean;
import com.avcdata.aoscustommade.fragment.SlideMenuFragment;
import com.avcdata.aoscustommade.main.BaseActivity;
import com.avcdata.aoscustommade.model.MainActivityModel;
import com.avcdata.aoscustommade.presenter.MainActivityPresenter;
import com.avcdata.aoscustommade.receiver.MyReceiver;
import com.avcdata.aoscustommade.utils.AppActivityManager;
import com.avcdata.aoscustommade.utils.AppUtils;
import com.avcdata.aoscustommade.utils.AvcConstants;
import com.avcdata.aoscustommade.utils.MyXValueFormatter;
import com.avcdata.aoscustommade.utils.ScreenUtils;
import com.avcdata.aoscustommade.utils.SharedPreferencesUtils;
import com.avcdata.aoscustommade.utils.TextUitl;
import com.avcdata.aoscustommade.utils.ToastUtils;
import com.avcdata.aoscustommade.utils.http.AvcHttpUtils;
import com.avcdata.aoscustommade.utils.http.AvcJsonHttpResponseHandler;
import com.avcdata.aoscustommade.utils.http.AvcJsonHttpResponseHandler;
import com.avcdata.aoscustommade.view.MainActivityView;
import com.avcdata.avcchart.linechart.chart.AvcLineCharts;
import com.github.mikephil.charting.charts.LineChart;
import com.avcdata.avcchart.linechart.piechart.AvcPieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.mxn.soul.flowingdrawer_core.FlowingView;
import com.mxn.soul.flowingdrawer_core.LeftDrawerLayout;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import static com.avcdata.aoscustommade.R.id.product_pie_noinfo;
import static com.avcdata.aoscustommade.R.id.productsituation;
import static com.avcdata.aoscustommade.utils.ToastUtils.showShort;

/***
 * 首页主页
 */
public class Main_Activity extends BaseActivity implements OnChartGestureListener, OnChartValueSelectedListener, MainActivityView {

    @ViewInject(R.id.leftImage)
    private ImageView leftImage;
    @ViewInject(R.id.leftText)
    private TextView leftText;
    @ViewInject(R.id.title)
    private TextView title;
    @ViewInject(R.id.rightText)
    private TextView rightText;
    @ViewInject(R.id.rightImage2)
    private ImageView rightImage;

    @ViewInject(R.id.id_drawerlayout)
    private LeftDrawerLayout mLeftDrawerLayout;
    @ViewInject(R.id.sv)
    private FlowingView mFlowingView;


    @ViewInject(R.id.listview)
    private ListView listview;

    //头部趋势图
    private View headView;
    private TextView module_name;
    private TextView module_type;
    private ImageView module_arrows;
    private LineChart linechart_view;
    private TextView trendtip_text;

    private SharedPreferencesUtils sp;

    //异常情况
    @ViewInject(R.id.loadfail)
    private View loadfail;
    @ViewInject(R.id.noinfo)
    private View noinfo;
    @ViewInject(R.id.jiazai_layout)
    private LinearLayout jiazai_layout;
    @ViewInject(R.id.load_fail_layout)
    private LinearLayout load_fail_layout;
    @ViewInject(R.id.content_lay)
    private View content_lay;

    /**
     * 大区域数据存储
     */
    public ArrayList<UserRegionBean> areaData = new ArrayList<>();

    /**
     * 办事处级数据储存
     */
    public ArrayList<ArrayList<UserRegionBean>> agencyData = new ArrayList<>();

    /**
     * 详情数据存储
     */
    public ArrayList<String> detailData = new ArrayList<>();
    //判断顺序
    public ArrayList<String> selectOrderData = new ArrayList<>();

    //线图顺序
    public ArrayList<String> selectTrendLineData = new ArrayList<>();

    private PopupWindow popupWindow;
    private ListView listViewPopup;
    private BaseHolderAdapter adapter;
    private ArrayList<String> dataPopup;
    private String module_typeString;

    private MyReceiver myReceiver;
    private MainActivityPresenter mainActivityPresenter;

    @Override
    public void initView() {
        setContentView(R.layout.activity_main);
        AppActivityManager.getAppManager().addActivity(this);
        ViewUtils.inject(this);
        headView = LayoutInflater.from(this).inflate(R.layout.head_linetrend, null);
//        listview.addHeaderView(headView);
        listview.addHeaderView(headView, null, false);
        module_name = (TextView) headView.findViewById(R.id.module_name);
        module_name.setText("A.O史密斯占有率走势");
        module_type = (TextView) headView.findViewById(R.id.module_type);
        module_arrows = (ImageView) headView.findViewById(R.id.module_arrows);
        linechart_view = (LineChart) headView.findViewById(R.id.linechart_view);
        trendtip_text = (TextView) headView.findViewById(R.id.trendtip_text);

    }

    @Override
    public void initInstall() {
        sp = new SharedPreferencesUtils(this);
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        myReceiver = new MyReceiver(loadfail);
        this.registerReceiver(myReceiver, filter);
        leftImage.setImageResource(R.mipmap.person);
        title.setText(getResources().getString(R.string.product_all));
        rightText.setText(getResources().getString(R.string.area_set));
        rightImage.setImageResource(R.mipmap.location);
        leftText.setVisibility(View.GONE);
        rightImage.setVisibility(View.VISIBLE);

        areaData = LocatityCacheData.areaData;
        agencyData = LocatityCacheData.agencyData;
        detailData = LocatityCacheData.detailData;

        FragmentManager fm = getSupportFragmentManager();
        SlideMenuFragment mMenuFragment = (SlideMenuFragment) fm.findFragmentById(R.id.id_container_menu);
        if (mMenuFragment == null) {
            fm.beginTransaction().add(R.id.id_container_menu, mMenuFragment = new SlideMenuFragment()).commit();
        }
        mLeftDrawerLayout.setFluidView(mFlowingView);
        mLeftDrawerLayout.setMenuFragment(mMenuFragment);

        mainActivityPresenter = new MainActivityPresenter(this, new MainActivityModel(Main_Activity.this));
    }

    @SuppressWarnings("deprecation")
    @Override
    public void initData() {
        trendtip_text.setText(sp.getNewWeek() + "品类综合概况");
        dataPopup = new ArrayList<>();
        dataPopup.add("全品类综合");
        dataPopup.add("热水器");
        dataPopup.add("燃气热水器");
        dataPopup.add("电储水热水器");
        dataPopup.add("净化器");
        dataPopup.add("净水器");
        selectOrderData.add("热水器");
        selectOrderData.add("燃气热水器");
        selectOrderData.add("电储水热水器");
        selectOrderData.add("净化器");
        selectOrderData.add("净水器");
        View single_listviewPopup = LayoutInflater.from(this).inflate(R.layout.single_listviewpopup, null);
//        single_listviewPopup.setBackgroundResource(R.mipmap.bg_popup_window);
        listViewPopup = (ListView) single_listviewPopup.findViewById(R.id.listViewPopup);
        popupWindow = new PopupWindow(single_listviewPopup, ScreenUtils.getScreenWidth(this) / 3, LinearLayout.LayoutParams.WRAP_CONTENT, true);

//        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        adapter = new BaseHolderAdapter(Main_Activity.this, dataPopup);
        adapter.setSelectPosition(0);
        module_typeString = adapter.getSelectString();
        module_type.setText(module_typeString);
        listViewPopup.setAdapter(adapter);
        load();

    }

    private void load() {
        if (module_typeString.equals("全品类综合")) {
            module_name.setText("A.O史密斯占有率走势");
        } else {
            module_name.setText(module_typeString + "占有率走势");
        }
        loadBrandList();
    }


    private void loading(boolean isFail, boolean isLoading, boolean isNoInfo) {
        if (isFail) {
            if (isLoading) {
                loadfail.setVisibility(View.GONE);
                load_fail_layout.setVisibility(View.GONE);
                jiazai_layout.setVisibility(View.GONE);
                content_lay.setVisibility(View.GONE);
                noinfo.setVisibility(View.GONE);
            } else {
                loadfail.setVisibility(View.VISIBLE);
                load_fail_layout.setVisibility(View.VISIBLE);
                jiazai_layout.setVisibility(View.GONE);
                content_lay.setVisibility(View.GONE);
                if (isNoInfo) {
                    load_fail_layout.setVisibility(View.GONE);
                    noinfo.setVisibility(View.VISIBLE);
                } else {
                    noinfo.setVisibility(View.GONE);
                }

            }
        } else {
            noinfo.setVisibility(View.GONE);
            if (isLoading) {
                loadfail.setVisibility(View.VISIBLE);
                load_fail_layout.setVisibility(View.GONE);
                jiazai_layout.setVisibility(View.VISIBLE);
                content_lay.setVisibility(View.GONE);
            } else {
                loadfail.setVisibility(View.GONE);
                load_fail_layout.setVisibility(View.GONE);
                jiazai_layout.setVisibility(View.GONE);
                content_lay.setVisibility(View.VISIBLE);
            }
        }
    }


    private void loadingTimeout() {
        loadfail.setVisibility(View.GONE);
        load_fail_layout.setVisibility(View.GONE);
        jiazai_layout.setVisibility(View.GONE);
        content_lay.setVisibility(View.GONE);
    }


    @Override
    public void evenControl() {
        leftImage.setOnClickListener(this);
        rightText.setOnClickListener(this);
        rightImage.setOnClickListener(this);
        module_type.setOnClickListener(this);
        module_arrows.setOnClickListener(this);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int index = Integer.valueOf(parent.getAdapter().getItemId(position) + "");//这是正确的Id
                if (isClickAbleDetail(salesData.get(index).get(1).get("category"))) {
                    Intent intent = new Intent(Main_Activity.this, CityDatail_Activity.class);
                    intent.putExtra("category", salesData.get(index).get(1).get("category"));
                    intent.putExtra("city", "");
                    startActivity(intent);
                }
            }
        });
    }


    @Override
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.leftImage:
                if (!mLeftDrawerLayout.isShownMenu()) {
                    mLeftDrawerLayout.toggle();
                }
                break;
            case R.id.rightText:
            case R.id.rightImage:
                if (isAbleClick()) {
                    Intent intent = new Intent(this, SelectBigArea_Activity.class);
                    intent.putExtra("isMain", true);
                    startActivity(intent);
                } else {
                    mLeftDrawerLayout.toggle();
                }
                break;
            case R.id.module_type:
            case R.id.module_arrows:
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    popupWindow.showAsDropDown(view);
                }

                break;

        }

        listViewPopup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                module_typeString = dataPopup.get(position);
                module_type.setText(module_typeString);
                popupWindow.dismiss();
                load();

            }
        });


    }

    private long startTime = 0;//开始点击的时间,全局变量

    /**
     * 是否可以点击
     *
     * @return
     */
    private boolean isAbleClick() {
        if (mLeftDrawerLayout.isShownMenu()) {
            return false;
        }
        return true;
    }


    /**
     * 获取品牌排行
     */
    private void loadBrandList() {
        loading(false, true, false);
        mainActivityPresenter.loadBrandList(module_typeString, 5, 51, sp.getNewWeek(), "all", "all", "all", "A.O.史密斯", AppUtils.getSimSerialNumber(Main_Activity.this));
    }

    /**
     * 获取品牌排行榜成功
     *
     * @param bean
     */
    @Override
    public void loadBrandListSuccess(TopBrandAndSelfBrandBean bean) {
        ArrayList<String> brandTopData = new ArrayList<>();
        try {
            if (bean != null) {
                boolean success = bean.isSuccess();
                String message = bean.getMessage();
                List<String> returnValue = bean.getReturnValue();
                if (success) {
                    if (returnValue != null && returnValue.size() > 0) {
                        for (int j = 0, k = returnValue.size(); j < k; j++) {
                            String keyString = returnValue.get(j).toString().trim();
                            if (keyString.equals("A.O.史密斯")) {
                                brandTopData.add(0, keyString);
                            } else {
                                brandTopData.add(keyString);
                            }
                        }
                        selectTrendLineData = brandTopData;
                        loadedType(true, message, 0);

                    } else {
                        loadedType(false, message, -1);
                    }
                } else {
                    loadedType(false, message, -1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取品牌排行榜失败
     */
    @Override
    public void loadBrandFailure() {
        loadedType(false, "", -1);
    }

    /**
     * 获取品牌排行榜失败
     *
     * @param throwable
     */
    @Override
    public void loadBrandFailure(Throwable throwable) {
        if (throwable instanceof ConnectTimeoutException || throwable instanceof SocketTimeoutException) {
            loadingTimeout();
        }
    }


    /**
     * 全国趋势图
     */
    private void loadNationalTrend() {
        mainActivityPresenter.loadNationalTrend(module_typeString, "A.O.史密斯", 5, 51, sp.getNewWeek(), "all", "all", "all");

    }

    /**
     * 全国走势图获取成功
     *
     * @param jsonObject
     */
    @Override
    public void loadNationThrendSuccess(JSONObject jsonObject) {
        String message = "";
        String returnValue = "";
        String secretKey;
        ArrayList<ArrayList<HashMap<String, String>>> trendData = new ArrayList<>();
        ArrayList<String> brandString = new ArrayList<>();
        try {
            if (!TextUitl.isEmpty(jsonObject.toString())) {
                boolean success = jsonObject.getBoolean("success");
                message = jsonObject.getString("message").trim();
                secretKey = jsonObject.getString("secretKey").trim();
                if (TextUitl.isEmpty(secretKey) || !sp.getKey().equals(secretKey)) {
                    ToastUtils.showShort(Main_Activity.this, "已在其他设备上登录,请重新登陆");
                    Intent intent = new Intent(Main_Activity.this, Login_Activity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                } else {
                    returnValue = jsonObject.getString("returnValue").trim();
                    if (success && jsonObject.has("returnValue")) {
                        if (!TextUitl.isEmpty(returnValue) || returnValue.equals("{}")) {
                            JSONObject returnValueObject = jsonObject.getJSONObject("returnValue");
                            Iterator iterator = returnValueObject.keys();
                            while (iterator.hasNext()) {
                                String key = iterator.next().toString().trim();
                                String value = returnValueObject.getString(key).trim();
                                brandString.add(key);
                                JSONArray array = returnValueObject.getJSONArray(key);
                                ArrayList<HashMap<String, String>> tempBrand = new ArrayList<>();
                                for (int a = 0; a < array.length(); a++) {
                                    JSONObject jsonobject = array.getJSONObject(a);
                                    HashMap<String, String> temp = new HashMap<>();
                                    temp.put("key", jsonobject.get("key").toString().trim());
                                    temp.put("value", jsonobject.get("value").toString().trim());
                                    tempBrand.add(temp);
                                }
                                trendData.add(tempBrand);
                            }
                            if (module_typeString.equals("全品类综合")) {
                                ArrayList<ArrayList<HashMap<String, String>>> trendDataTemp = new ArrayList<>();
                                ArrayList<String> brandStringTemp = new ArrayList<>();
                                for (int j = 0, k = brandString.size(); j < k; j++) {
                                    ArrayList<HashMap<String, String>> trendDataTemp0 = new ArrayList<>();
                                    brandStringTemp.add(brandString.get(sequenceIndex(j, brandString)));
                                    trendDataTemp0 = trendData.get(sequenceIndex(j, brandString));
                                    trendDataTemp.add(trendDataTemp0);
                                }
                                trendData = trendDataTemp;
                                brandString = brandStringTemp;
                            } else {
                                ArrayList<ArrayList<HashMap<String, String>>> trendDataTemp = new ArrayList<>();
                                ArrayList<String> brandStringTemp = new ArrayList<>();
                                for (int j = 0, k = brandString.size(); j < k; j++) {
                                    ArrayList<HashMap<String, String>> trendDataTemp0 = new ArrayList<>();
                                    brandStringTemp.add(brandString.get(sequenceTrendIndex(j, brandString)));
                                    trendDataTemp0 = trendData.get(sequenceTrendIndex(j, brandString));
                                    trendDataTemp.add(trendDataTemp0);
                                }
                                trendData = trendDataTemp;
                                brandString = brandStringTemp;
                            }
                            initNationalTrendData(trendData, brandString);
                            loadedType(true, message, 1);

                        } else {
                            loadedType(false, message, -1);
                        }
                    } else {
                        loadedType(false, message, -1);
                    }

                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 全国走势图获取失败
     */
    @Override
    public void loadNationThrendFailure() {
        loadedType(false, "", -1);
    }

    /**
     * 全国走势图获取失败
     *
     * @param throwable
     */
    @Override
    public void loadNationThrendFailure(Throwable throwable) {
        if (throwable instanceof ConnectTimeoutException ||
                throwable instanceof SocketTimeoutException) {
            loadingTimeout();
        }
    }



    private int sequenceTrendIndex(int index, ArrayList<String> brandStringTemp) {
        for (int i = index, j = selectTrendLineData.size(); i < j; i++) {
            for (int k = 0; k < brandStringTemp.size(); k++) {
                if (selectTrendLineData.get(i).equals(brandStringTemp.get(k))) {
                    return k;
                }
            }
        }
        return index;
    }


    private int sequenceIndex(int index, ArrayList<String> brandStringTemp) {
        for (int i = index, j = selectOrderData.size(); i < j; i++) {
            for (int k = 0; k < brandStringTemp.size(); k++) {
                if (selectOrderData.get(i).equals(brandStringTemp.get(k))) {
                    return k;
                }
            }
        }
        return index;
    }


    @SuppressWarnings("deprecation")
    private void initNationalTrendData(ArrayList<ArrayList<HashMap<String, String>>> data, ArrayList<String> key) {
        //设置手势滑动事件
        linechart_view.setOnChartGestureListener(Main_Activity.this);
        //设置数值选择监听
        linechart_view.setOnChartValueSelectedListener(this);
        //后台绘制
        linechart_view.setDrawGridBackground(false);

        //设置描述文本
        linechart_view.getDescription().setEnabled(false);
        // enable touch gestures
        linechart_view.setTouchEnabled(true); // 设置是否可以触摸
        linechart_view.setDragEnabled(true);// 是否可以拖拽
//        linechart_view.setClickable(false);
//        linechart_view.setClipValuesToContent(false);
//        linechart_view.setContextClickable(false);
        linechart_view.setScaleEnabled(false);// 是否可以缩放 x和y轴, 默认是true
        linechart_view.setPinchZoom(false);  //设置x轴和y轴能否同时缩放。默认是否
        linechart_view.setDoubleTapToZoomEnabled(false);//设置是否可以通过双击屏幕放大图表。默认是true
        linechart_view.setHighlightPerDragEnabled(false);//能否拖拽高亮线(数据点与坐标的提示线)，默认是true
        linechart_view.setDragDecelerationEnabled(false);//拖拽滚动时，手放开是否会持续滚动，默认是true（false是拖到哪是哪，true拖拽之后还会有缓冲）
        linechart_view.setDragDecelerationFrictionCoef(0.99f);//与上面那个属性配合，持续滚动时的速度快慢，[0,1) 0代表立即停止。
        linechart_view.setFocusableInTouchMode(false);
//        linechart_view.setTouchscreenBlocksFocus(false);
        // 是否在折线图上添加边框
        linechart_view.setDrawBorders(false);
        linechart_view.setNoDataText("没有相关数据");

        if (data.size() != 0) {
            linechart_view.moveViewToX(getWeekXCoord(data).size());
        }

        //设置X轴
        XAxis xAxis = linechart_view.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTextSize(8f);
        xAxis.setTextColor(getResources().getColor(R.color.text_color));
        xAxis.setDrawAxisLine(true);
        xAxis.setDrawGridLines(false);
        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);
        xAxis.setAvoidFirstLastClipping(true);

        if (data.size() != 0) {
            xAxis.setValueFormatter(new MyXValueFormatter(getWeekXCoord(data)));
        }

        YAxis leftAxis = linechart_view.getAxis(YAxis.AxisDependency.LEFT);//确定表示图表的侧面
        linechart_view.getAxisRight().setEnabled(false);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setTextSize(8f);
        leftAxis.setTextColor(getResources().getColor(R.color.text_color));
//        leftAxis.setDrawZeroLine(true);
        leftAxis.setDrawAxisLine(true);
        leftAxis.setDrawGridLines(true);
//        leftAxis.resetAxisMinValue();
        leftAxis.enableGridDashedLine(2f, 10f, 1f);
        if (data.size() != 0) {
            //y轴最小
            leftAxis.setAxisMinValue(getMinYValue(data, key));
            //y轴最大
            leftAxis.setAxisMaxValue(getMaxYValue(data, key));
        }

        // 限制数据(而不是背后的线条勾勒出了上面)
        leftAxis.setDrawLimitLinesBehindData(true);

        // 设置比例图标示，就是那个一组y的value的
        Legend mLegend = linechart_view.getLegend();
        mLegend.setPosition(Legend.LegendPosition.ABOVE_CHART_CENTER);
        mLegend.setForm(Legend.LegendForm.LINE);// 样式
        mLegend.setFormSize(15.0f);// 字体
        mLegend.setWordWrapEnabled(true);
        mLegend.setTextColor(Color.DKGRAY);// 颜色

//        Matrix matrix = new Matrix();
//        int tempSize = getWeekXCoord(data).size();
//        matrix.postScale(tempSize / 8, 1f);
//        // 在图表动画显示之前进行缩放
//        linechart_view.getViewPortHandler().refresh(matrix, linechart_view, false);

        if (data.size() != 0) {
            //设置数据
            trendDataAmend(data, key);
            linechart_view.setVisibleXRangeMaximum(8);
        }

        //默认动画
        linechart_view.animateX(1000);
//        linechart_view.animateXY(1000,1000);

        linechart_view.invalidate();

    }

    //获取星期数
    private ArrayList<String> getWeekXCoord(ArrayList<ArrayList<HashMap<String, String>>> data) {
        ArrayList<String> temp = new ArrayList<>();
//        Log.e("data","--------获取星期数---------"+data.size());
        for (int a = 0, b = data.get(0).size(); a < b; a++) {
            HashMap<String, String> hashMap = data.get(0).get(a);
            String key = hashMap.get("key").toString().trim();
            String value = hashMap.get("value").toString().trim();
            temp.add(key);

        }
        return temp;
    }


    //获取最大值
    private float getMaxYValue(ArrayList<ArrayList<HashMap<String, String>>> data, ArrayList<String> keyBrand) {
        float endValue = 20f;
        for (int i = 0; i < keyBrand.size(); i++) {
            for (int a = 0, b = data.get(i).size(); a < b; a++) {
                HashMap<String, String> hashMap = data.get(i).get(a);
                String key = hashMap.get("key").toString().trim();
                String value = hashMap.get("value").toString().trim();
                if (!TextUitl.isEmpty(value)) {
                    float tempValue = Float.valueOf(value);
                    endValue = tempValue > endValue ? tempValue : endValue;
                }
            }

        }
        return Math.round(endValue + 10f);
    }


    //获取最小值
    private float getMinYValue(ArrayList<ArrayList<HashMap<String, String>>> data, ArrayList<String> keyBrand) {
        float endValue = -2f;
        for (int i = 0; i < keyBrand.size(); i++) {
            for (int a = 0, b = data.get(i).size(); a < b; a++) {
                HashMap<String, String> hashMap = data.get(i).get(a);
                String key = hashMap.get("key").toString().trim();
                String value = hashMap.get("value").toString().trim();
                if (!TextUitl.isEmpty(value)) {
                    float tempValue = Float.valueOf(value);
                    endValue = tempValue < endValue ? tempValue : endValue;
                }
            }

        }
        return Math.round(endValue - 2f);
    }


    //线性图数据
    @SuppressWarnings("deprecation")
    private void trendDataAmend(ArrayList<ArrayList<HashMap<String, String>>> data, ArrayList<String> keyBrand) {
        ArrayList<String> xString = new ArrayList<>();//X坐标的值
        ArrayList<ILineDataSet> mLineDataSets = new ArrayList<>();

        for (int i = 0; i < keyBrand.size(); i++) {
            ArrayList<Entry> yString = new ArrayList<>();//Y坐标的值
            for (int a = 0, b = data.get(i).size(); a < b; a++) {
                HashMap<String, String> hashMap = data.get(i).get(a);
                String key = hashMap.get("key").toString().trim();
                String value = hashMap.get("value").toString().trim();
                xString.add(key);
                if (TextUitl.isEmpty(value)) {
                    if (data.get(i).size() < 8) {
                        yString.add(new Entry(a + 1, 0));
                    } else {
                        yString.add(new Entry(a, 0));
                    }
                } else {
                    if (data.get(i).size() < 8) {
                        yString.add(new Entry(a + 1, TextUitl.retainTwoDecimalsFloat(value)));
                    } else {
                        yString.add(new Entry(a, TextUitl.retainTwoDecimalsFloat(value)));
                    }
                }
            }
            // y轴数据集
            LineDataSet mLineDataSet = new LineDataSet(yString, keyBrand.get(i));

            mLineDataSet.setDrawValues(false);
            // 线宽
            mLineDataSet.setLineWidth(1.0f);
            // 显示的圆形大小
            mLineDataSet.setCircleSize(2.0f);
            mLineDataSet.setDrawCircleHole(true);
            // 折线的颜色
            mLineDataSet.setColor(TextUitl.getColor().get(i));
//            mLineDataSet.setColors(TextUitl.getColor());
            // 圆球的颜色
            mLineDataSet.setCircleColor(TextUitl.getColor().get(i));
//            mLineDataSet.setCircleColors(TextUitl.getColor());
            // 填充曲线下方的区域，红色，半透明。
            mLineDataSet.setDrawFilled(false);
            mLineDataSet.setFillAlpha(40);
            mLineDataSet.setFillColor(TextUitl.getColor().get(i));
            mLineDataSets.add(mLineDataSet);

        }
        LineData mLineData = new LineData(mLineDataSets);
        linechart_view.getXAxis().setAxisMaximum(mLineData.getXMax() + 1);
        linechart_view.setData(mLineData);

    }


    private Float clearUpData(String key) {
        if (TextUitl.isEmpty(key)) {
            return 2f;
        }

        String[] array = key.split("W");


        return 1f;


    }


    /**
     * 行业销售额同环比
     */
    private ArrayList<String> brandString;

    private void loadIndustrySales() {
        mainActivityPresenter.loadIndustrySales(sp.getNewWeek());
        brandString = new ArrayList<>();
    }

    /**
     * 获取行业销售额同环比成功
     * @param jsonObject
     */
    @Override
    public void loadIndustrySalesSuccess(JSONObject jsonObject) {
        String message = "";
        String returnValue = "";
        ArrayList<ArrayList<HashMap<String, String>>> salesDataAmountRatio = new ArrayList<>();
        try {
            if (!TextUitl.isEmpty(jsonObject.toString())) {
                boolean success = jsonObject.getBoolean("success");
                message = jsonObject.getString("message").trim();
                returnValue = jsonObject.getString("returnValue").trim();
                if (success && jsonObject.has("returnValue")) {
                    if (!TextUitl.isEmpty(returnValue) || returnValue.equals("{}")) {
                        JSONObject returnValueObject = jsonObject.getJSONObject("returnValue");
                        Iterator iterator = returnValueObject.keys();
                        while (iterator.hasNext()) {
                            String key = iterator.next().toString().trim();
                            String value = returnValueObject.getString(key).trim();
                            brandString.add(key);
                            JSONArray array = new JSONArray(value);
                            ArrayList<HashMap<String, String>> temp = new ArrayList<HashMap<String, String>>();
                            String tempCategory = "";
                            for (int a = 0; a < array.length(); a++) {
                                JSONObject jsonobject = array.getJSONObject(a);
                                HashMap<String, String> tempHash = new HashMap<>();
                                tempHash.put("basisValue", jsonobject.get("basisValue").toString().trim());
                                tempCategory = jsonobject.get("category").toString().trim();
                                tempHash.put("category", tempCategory);
                                tempHash.put("key", jsonobject.get("key").toString().trim());
                                tempHash.put("relativeValue", jsonobject.get("relativeValue").toString().trim());
                                if (TextUitl.isEmpty(jsonobject.get("value").toString().trim())) {
                                    tempHash.put("value", jsonobject.get("value").toString().trim());
                                } else {
                                    tempHash.put("value", new BigDecimal(jsonobject.get("value").toString().trim()) + "");
                                }
                                temp.add(tempHash);
                            }
                            salesDataAmountRatio.add(temp);
                        }
                        ArrayList<ArrayList<HashMap<String, String>>> trendDataTemp = new ArrayList<>();
                        ArrayList<String> brandStringTemp = new ArrayList<>();
                        for (int j = 0, k = brandString.size(); j < k; j++) {
                            ArrayList<HashMap<String, String>> trendDataTemp0 = new ArrayList<>();
                            brandStringTemp.add(brandString.get(sequenceIndex(j, brandString)));
                            trendDataTemp0 = salesDataAmountRatio.get(sequenceIndex(j, brandString));
                            trendDataTemp.add(trendDataTemp0);
                        }
                        brandString = brandStringTemp;
                        salesData = trendDataTemp;
                        loadPiePicture();
                    } else {
                        loadedType(false, message, -1);
                    }

                } else {
                    loadedType(false, message, -1);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            loadedType(false, message, -1);
        }

    }

    /**
     * 获取行业同环比失败
     */
    @Override
    public void loadIndustrySalesFailure() {
        loadedType(false, "", -1);
    }

    /**
     * 获取行业同环比失败
     * @param throwable
     */
    @Override
    public void loadIndustrySalesFailure(Throwable throwable) {
        if (throwable instanceof ConnectTimeoutException ||
                throwable instanceof SocketTimeoutException) {
            loadingTimeout();
        }
    }

    /**
     * 行业市占饼图
     */
    private BigAreaAdapter bigAreaAdapter;//饼图适配器
    private ArrayList<String> brandPieString;
    private ArrayList<ArrayList<HashMap<String, String>>> pieData = new ArrayList<>();
    private void loadPiePicture() {
        mainActivityPresenter.loadPiePicture(sp.getNewWeek());
        brandPieString = new ArrayList<>();
    }

    @Override
    public void loadPiePictureSuccess(JSONObject jsonObject) {
        String message = "";
        String returnValue = "";

        try {
            if (!TextUitl.isEmpty(jsonObject.toString())) {
                pieData.clear();
                boolean success = jsonObject.getBoolean("success");
                message = jsonObject.getString("message").trim();
                returnValue = jsonObject.getString("returnValue").trim();
                if (success && jsonObject.has("returnValue")) {
                    if (!TextUitl.isEmpty(returnValue) || returnValue.equals("{}")) {
                        JSONObject returnValueObject = jsonObject.getJSONObject("returnValue");
                        Iterator iterator = returnValueObject.keys();
                        while (iterator.hasNext()) {
                            String key = iterator.next().toString().trim();
                            String value = returnValueObject.getString(key).trim();
                            brandPieString.add(key);
                            JSONArray array = new JSONArray(value);
                            ArrayList<HashMap<String, String>> temp = new ArrayList<HashMap<String, String>>();
                            String tempCategory = "";
                            for (int a = 0; a < array.length(); a++) {
                                JSONObject jsonobject = array.getJSONObject(a);
                                Log.e("数值", "长度－－－－"+ array.length()+"---a---"+a);
                                HashMap<String, String> tempHash = new HashMap<String, String>();

                                tempHash.put("basisValue", jsonobject.get("basisValue").toString().trim());
                                tempCategory = jsonobject.get("category").toString().trim();
                                tempHash.put("category", tempCategory);
                                tempHash.put("key", jsonobject.get("key").toString().trim());
                                tempHash.put("relativeValue", jsonobject.get("relativeValue").toString().trim());
                                tempHash.put("value", jsonobject.get("value").toString().trim());
                                temp.add(tempHash);
                            }
                            pieData.add(temp);
                        }
                        ArrayList<ArrayList<HashMap<String, String>>> trendDataTemp = new ArrayList<>();
                        for (int j = 0, k = brandString.size(); j < k; j++) {
                            ArrayList<HashMap<String, String>> trendDataTemp0 = new ArrayList<>();
                            trendDataTemp0 = pieData.get(sequencePieIndex(j, brandString, brandPieString));
                            trendDataTemp.add(trendDataTemp0);
                        }
                        pieData = trendDataTemp;
                        bigAreaAdapter = new BigAreaAdapter();
                        listview.setAdapter(bigAreaAdapter);
                    } else {
                        loadedType(false, message, -1);
                    }
                } else {
                    loadedType(false, message, -1);
                }
                loading(false, false, false);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            loadedType(false, message, -1);
        }
    }

    @Override
    public void loadPiePictureFailure() {
        loadedType(false, "", -1);
        loading(false, false, false);
    }

    @Override
    public void loadPiePictureFailure(Throwable throwable) {
        if (throwable instanceof ConnectTimeoutException ||
                throwable instanceof SocketTimeoutException) {
            loadingTimeout();
            loading(false, false, false);
        }
    }

    //综合品类顺序排序
    private int sequencePieIndex(int index, ArrayList<String> brandStringTemp, ArrayList<String> pieData) {
        for (int i = index, j = brandStringTemp.size(); i < j; i++) {
            for (int k = 0; k < pieData.size(); k++) {
                if (brandStringTemp.get(i).equals(pieData.get(k))) {
                    return k;
                }
            }
        }
        return index;
    }

    //其他种类位置
    private int sequenceOtherIndex(ArrayList<String> brandStringTemp) {
        int index = 0;
        for (int i = 0, j = brandStringTemp.size(); i < j; i++) {
            if (brandStringTemp.get(i).equals(module_typeString)) {
                index = i;
                return index;
            }
        }
        return index;
    }


    //集合中两个数据互换位置
    public <T> ArrayList<T> indexExChange(ArrayList<T> list, int index1, int index2) {
        T t = list.get(index1);
        list.set(index1, list.get(index2));
        list.set(index2, t);
        return list;
    }


    private void loadedType(boolean isSuccess, String messaage, int number) {
        if (isSuccess) {
            if (number == 0) {
                loadNationalTrend();
            } else if (number == 1) {
                if (module_typeString.equals("全品类综合")) {
                    loadIndustrySales();
                } else {
                    int brandIndex = sequenceOtherIndex(brandString);
                    brandString = indexExChange(brandString, 0, brandIndex);
                    salesData = indexExChange(salesData, 0, brandIndex);
                    Log.e("位置", "位置2-------" + pieData.size());
                    pieData = indexExChange(pieData, 0, brandIndex);
                    bigAreaAdapter.notifyDataSetChanged();
                    loading(false, false, false);
                }
            }
        } else {
            if (!TextUitl.isEmpty(messaage) && "用户已过期，请重新登录".equals(messaage)) {
                Intent intent = new Intent(Main_Activity.this, Login_Activity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            } else {
                loading(true, false, false);
                if (messaage.equals("ok!")) {
                    loading(true, false, true);
                    return;
                }
            }
        }

    }


    private ArrayList<ArrayList<HashMap<String, String>>> salesData = new ArrayList<>();


    private class BigAreaAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return salesData.size();
        }

        @Override
        public Object getItem(int position) {
            return salesData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressWarnings("deprecation")
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder vHolder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(Main_Activity.this).inflate(R.layout.item_productsituation, null);
                vHolder = new ViewHolder();

                vHolder.productsituation = (View) convertView.findViewById(productsituation);

                vHolder.product_type = (ImageView) convertView.findViewById(R.id.product_type);
                vHolder.product_name = (TextView) convertView.findViewById(R.id.product_name);
                vHolder.product_details = (TextView) convertView.findViewById(R.id.product_details);
                vHolder.product_arrows = (ImageView) convertView.findViewById(R.id.product_arrows);

                vHolder.industry_sales = (TextView) convertView.findViewById(R.id.industry_sales);
                vHolder.industry_salesTag = (TextView) convertView.findViewById(R.id.industry_salesTag);
                vHolder.industry_relative = (TextView) convertView.findViewById(R.id.industry_relative);
                vHolder.industry_basis = (TextView) convertView.findViewById(R.id.industry_basis);

                vHolder.brand_sales = (TextView) convertView.findViewById(R.id.brand_sales);
                vHolder.brand_salesTag = (TextView) convertView.findViewById(R.id.brand_salesTag);
                vHolder.brand_relative = (TextView) convertView.findViewById(R.id.brand_relative);
                vHolder.brand_basis = (TextView) convertView.findViewById(R.id.brand_basis);

                vHolder.product_pie = (AvcPieChart) convertView.findViewById(R.id.product_pie);
                vHolder.product_pie_noinfo = (TextView) convertView.findViewById(product_pie_noinfo);

                convertView.setTag(vHolder);
            } else {
                vHolder = (ViewHolder) convertView.getTag();
            }
            ArrayList<HashMap<String, String>> salesOuterData = salesData.get(position);
            HashMap<String, String> salesOuterData0 = salesOuterData.get(0);
            HashMap<String, String> salesOuterData1 = salesOuterData.get(1);

            if (salesOuterData1.get("category").equals("热水器")) {
                vHolder.product_type.setImageResource(R.mipmap.product_electricwaterheater);
            } else if (salesOuterData1.get("category").equals("净化器")) {
                vHolder.product_type.setImageResource(R.mipmap.product_aircleaner);
            } else if (salesOuterData1.get("category").equals("净水器")) {
                vHolder.product_type.setImageResource(R.mipmap.product_watercleaner);
            } else if (salesOuterData1.get("category").equals("电储水热水器")) {
                vHolder.product_type.setImageResource(R.mipmap.product_electricwaterheater);
            } else {
                vHolder.product_type.setImageResource(R.mipmap.product_gaswaterheater);
            }
            vHolder.product_name.setText(salesOuterData0.get("category"));


            if (isClickAbleDetail(salesOuterData1.get("category"))) {
                vHolder.product_details.setVisibility(View.VISIBLE);
                vHolder.product_arrows.setVisibility(View.VISIBLE);
            } else {
                vHolder.product_details.setVisibility(View.GONE);
                vHolder.product_arrows.setVisibility(View.GONE);
            }


            //行业
            String tempValueIndustry = salesOuterData1.get("value");
//            Log.e("string","-----行业给的数据-------"+tempValueIndustry);
            if (TextUitl.isEmpty(tempValueIndustry)) {
                vHolder.industry_sales.setText("--");
                vHolder.industry_salesTag.setText("");
            } else {
                tempValueIndustry = new BigDecimal(tempValueIndustry) + "";
                if (Math.round(Float.valueOf(tempValueIndustry)) >= 100000000) {
                    vHolder.industry_sales.setText(TextUitl.retainTwoDecimalsString(Float.valueOf(tempValueIndustry) / 100000000) + "");
                    vHolder.industry_salesTag.setText("亿元");
                } else if (Math.round(Float.valueOf(tempValueIndustry)) < 100000000f && Math.round(Float.valueOf(tempValueIndustry)) >= 10000f) {
                    vHolder.industry_sales.setText(TextUitl.retainTwoDecimalsString(Float.valueOf(tempValueIndustry) / 10000) + "");
                    vHolder.industry_salesTag.setText("万元");
                } else {
                    vHolder.industry_sales.setText(TextUitl.retainTwoDecimalsString(Float.valueOf(tempValueIndustry)) + "");
                    vHolder.industry_salesTag.setText("元");
                }

            }


            Drawable drawable_relative = null;
            if (TextUitl.isEmpty(salesOuterData1.get("relativeValue"))) {
                vHolder.industry_relative.setTextColor(getResources().getColor(R.color.text_color));
                drawable_relative = getResources().getDrawable(R.drawable.square_white);
                vHolder.industry_relative.setText("--");
            } else {
                if (TextUitl.isUp(salesOuterData1.get("relativeValue"))) {
                    drawable_relative = getResources().getDrawable(R.drawable.data_rise);
                    vHolder.industry_relative.setTextColor(getResources().getColor(R.color.green));
                } else {
                    drawable_relative = getResources().getDrawable(R.drawable.data_decline);
                    vHolder.industry_relative.setTextColor(getResources().getColor(R.color.red));
                }
                vHolder.industry_relative.setText(TextUitl.retainTwoDecimals(salesOuterData1.get("relativeValue")));
            }
            drawable_relative.setBounds(0, 0, 20, 25);
            vHolder.industry_relative.setCompoundDrawables(drawable_relative, null, null, null);


            Drawable drawable_basis = null;
            if (TextUitl.isEmpty(salesOuterData1.get("basisValue"))) {
                vHolder.industry_basis.setTextColor(getResources().getColor(R.color.text_color));
                drawable_basis = getResources().getDrawable(R.drawable.square_white);
                vHolder.industry_basis.setText("--");
            } else {

                if (TextUitl.isUp(salesOuterData1.get("basisValue"))) {
                    drawable_basis = getResources().getDrawable(R.drawable.data_rise);
                    vHolder.industry_basis.setTextColor(getResources().getColor(R.color.green));
                } else {
                    drawable_basis = getResources().getDrawable(R.drawable.data_decline);
                    vHolder.industry_basis.setTextColor(getResources().getColor(R.color.red));
                }
                vHolder.industry_basis.setText(TextUitl.retainTwoDecimals(salesOuterData1.get("basisValue")));
            }
            drawable_basis.setBounds(0, 0, 20, 25);
            vHolder.industry_basis.setCompoundDrawables(drawable_basis, null, null, null);


            //品牌
            String tempValueBrand = salesOuterData0.get("value");
            if (TextUitl.isEmpty(tempValueBrand)) {
                vHolder.brand_sales.setText("--");
                vHolder.brand_salesTag.setText("");
            } else {
                tempValueBrand = new BigDecimal(tempValueBrand) + "";
                if (Math.round(Float.valueOf(tempValueBrand)) >= 100000000) {
                    vHolder.brand_sales.setText(TextUitl.retainTwoDecimalsString(Float.valueOf(tempValueBrand) / 100000000) + "");
                    vHolder.brand_salesTag.setText("亿元");
                } else if (Math.round(Float.valueOf(tempValueBrand)) < 100000000f && Math.round(Float.valueOf(tempValueBrand)) >= 10000f) {
                    vHolder.brand_sales.setText(TextUitl.retainTwoDecimalsString(Float.valueOf(tempValueBrand) / 10000) + "");
                    vHolder.brand_salesTag.setText("万元");
                } else {
                    vHolder.brand_sales.setText(TextUitl.retainTwoDecimalsString(Float.valueOf(tempValueBrand)) + "");
                    vHolder.brand_salesTag.setText("元");
                }
            }

            Drawable drawable_relative_brand = null;
            if (TextUitl.isEmpty(salesOuterData0.get("relativeValue"))) {
                vHolder.brand_relative.setTextColor(getResources().getColor(R.color.text_color));
                drawable_relative_brand = getResources().getDrawable(R.drawable.square_white);
                vHolder.brand_relative.setText("--");
            } else {
                if (TextUitl.isUp(salesOuterData0.get("relativeValue"))) {
                    drawable_relative_brand = getResources().getDrawable(R.drawable.data_rise);
                    vHolder.brand_relative.setTextColor(getResources().getColor(R.color.green));
                } else {
                    drawable_relative_brand = getResources().getDrawable(R.drawable.data_decline);
                    vHolder.brand_relative.setTextColor(getResources().getColor(R.color.red));
                }
                vHolder.brand_relative.setText(TextUitl.retainTwoDecimals(salesOuterData0.get("relativeValue")));
            }
            drawable_relative_brand.setBounds(0, 0, 20, 25);
            vHolder.brand_relative.setCompoundDrawables(drawable_relative_brand, null, null, null);

            Drawable drawable_basis_brand = null;
            if (TextUitl.isEmpty(salesOuterData0.get("basisValue"))) {
                vHolder.brand_basis.setTextColor(getResources().getColor(R.color.text_color));
                drawable_basis_brand = getResources().getDrawable(R.drawable.square_white);
                vHolder.brand_basis.setText("--");
            } else {
                if (TextUitl.isUp(salesOuterData0.get("basisValue"))) {
                    drawable_basis_brand = getResources().getDrawable(R.drawable.data_rise);
                    vHolder.brand_basis.setTextColor(getResources().getColor(R.color.green));
                } else {
                    drawable_basis_brand = getResources().getDrawable(R.drawable.data_decline);
                    vHolder.brand_basis.setTextColor(getResources().getColor(R.color.red));
                }
                vHolder.brand_basis.setText(TextUitl.retainTwoDecimals(salesOuterData0.get("basisValue")));
            }
            drawable_basis_brand.setBounds(0, 0, 20, 25);
            vHolder.brand_basis.setCompoundDrawables(drawable_basis_brand, null, null, null);


            ArrayList<HashMap<String, String>> pieOuterData = pieData.get(position);

            if (pieOuterData.size() == 0) {
                vHolder.product_pie_noinfo.setVisibility(View.VISIBLE);
                vHolder.product_pie.setVisibility(View.GONE);
            } else {
                vHolder.product_pie_noinfo.setVisibility(View.GONE);
                vHolder.product_pie.setVisibility(View.VISIBLE);
                vHolder.product_pie.setUsePercentValues(true);
                vHolder.product_pie.setCenterTextRadiusPercent(1.0f);
                vHolder.product_pie.setDragDecelerationEnabled(false);
                vHolder.product_pie.setNoDataText("没有相关数据");
                vHolder.product_pie.getDescription().setText("");
                vHolder.product_pie.setDrawCenterText(false);
                vHolder.product_pie.setDrawHoleEnabled(false);
                vHolder.product_pie.setDrawEntryLabels(false);
                vHolder.product_pie.setRotationEnabled(false);
                vHolder.product_pie.setHighlightPerTapEnabled(false);
                vHolder.product_pie.setDrawSlicesUnderHole(true);
                vHolder.product_pie.setTouchEnabled(false);

                Legend mLegend = vHolder.product_pie.getLegend(); //设置比例图
                mLegend.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
                mLegend.setYEntrySpace(0.2f);
                mLegend.setWordWrapEnabled(true);
                mLegend.setTextSize(2f);
                mLegend.setForm(Legend.LegendForm.SQUARE);
                mLegend.setEnabled(true);

                ArrayList<PieEntry> entries = new ArrayList<>();

                for (int i = 0, j = pieOuterData.size(); i < j; i++) {
                    HashMap<String, String> pieOuterDataHash = pieOuterData.get(i);
//                if (pieOuterDataHash.get("category").equals(salesOuterData1.get("category"))) {
                    if (TextUitl.isEmpty(pieOuterDataHash.get("value"))) {
                        entries.add(new PieEntry(TextUitl.retainTwoDecimalsFloat("0"), pieOuterDataHash.get("key")));
                    } else {
                        entries.add(new PieEntry(TextUitl.retainTwoDecimalsFloat(pieOuterDataHash.get("value")), pieOuterDataHash.get("key")));
                    }
                }
                PieDataSet pieDataSet = new PieDataSet(entries, "");
                pieDataSet.setSliceSpace(0.2f);
                pieDataSet.setColors(TextUitl.getColor());
                pieDataSet.setValueFormatter(new IValueFormatter() {
                    @Override
                    public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                        return TextUitl.retainTwoDecimalsString(value) + "%";
                    }
                });
                PieData pieData = new PieData(pieDataSet);
                vHolder.product_pie.setData(pieData);

                vHolder.product_pie.invalidate();
                notifyDataSetChanged();
            }
            return convertView;
        }


    }

    private boolean isClickAbleDetail(String string) {
        if (detailData.contains(string)) {
            return true;
        }
        return false;
    }


    private class ViewHolder {
        View productsituation;

        ImageView product_type;
        TextView product_name;
        TextView product_details;
        ImageView product_arrows;

        TextView industry_sales;
        TextView industry_salesTag;
        TextView industry_relative;
        TextView industry_basis;

        TextView brand_sales;
        TextView brand_salesTag;
        TextView brand_relative;
        TextView brand_basis;

        AvcPieChart product_pie;
        TextView product_pie_noinfo;

    }


    @Override
    public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {

    }

    @Override
    public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
// 完成之后停止晃动
        if (lastPerformedGesture != ChartTouchListener.ChartGesture.SINGLE_TAP)
            linechart_view.highlightValues(null);
    }

    @Override
    public void onChartLongPressed(MotionEvent me) {

    }

    @Override
    public void onChartDoubleTapped(MotionEvent me) {

    }

    @Override
    public void onChartSingleTapped(MotionEvent me) {

    }

    @Override
    public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {

    }

    @Override
    public void onChartScale(MotionEvent me, float scaleX, float scaleY) {

    }

    @Override
    public void onChartTranslate(MotionEvent me, float dX, float dY) {

    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(myReceiver);
    }

    @Override
    public void onBackPressed() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        } else {
            if (mLeftDrawerLayout.isShownMenu()) {
                mLeftDrawerLayout.closeDrawer();
            } else {
                if (System.currentTimeMillis() - startTime > AvcConstants.EXITTIME) {
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.exit_again), Toast.LENGTH_SHORT).show();
                    startTime = System.currentTimeMillis();
                } else {
                    AppActivityManager.getAppManager().finishAllActivity();
                }

            }
        }
    }


}
